const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'community_service_platform',
  port: 3306
};

async function testConnection() {
  try {
    console.log('🔍 正在测试数据库连接...');
    
    // 创建连接
    const connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 查看数据库信息
    const [dbInfo] = await connection.execute('SELECT DATABASE() as db_name');
    console.log(`📊 当前数据库: ${dbInfo[0].db_name}`);
    
    // 查看所有表
    const [tables] = await connection.execute('SHOW TABLES');
    console.log('📋 数据表列表:');
    tables.forEach(table => {
      const tableName = Object.values(table)[0];
      console.log(`   - ${tableName}`);
    });
    
    // 检查是否有闲置物品相关的表
    const idleItemsTable = tables.find(table => 
      Object.values(table)[0].toLowerCase().includes('idle') || 
      Object.values(table)[0].toLowerCase().includes('item')
    );
    
    if (idleItemsTable) {
      const tableName = Object.values(idleItemsTable)[0];
      console.log(`\n🔍 检查表结构: ${tableName}`);
      
      // 查看表结构
      const [columns] = await connection.execute(`DESCRIBE ${tableName}`);
      console.log('📝 表结构:');
      columns.forEach(col => {
        console.log(`   - ${col.Field}: ${col.Type} ${col.Null === 'YES' ? '(可空)' : '(非空)'}`);
      });
      
      // 查看数据
      const [data] = await connection.execute(`SELECT COUNT(*) as count FROM ${tableName}`);
      console.log(`📊 数据条数: ${data[0].count}`);
      
      if (data[0].count > 0) {
        const [sampleData] = await connection.execute(`SELECT * FROM ${tableName} LIMIT 3`);
        console.log('📄 示例数据:');
        sampleData.forEach((row, index) => {
          console.log(`   记录 ${index + 1}:`, row);
        });
      }
    }
    
    // 检查是否有技能相关的表
    const skillsTable = tables.find(table => 
      Object.values(table)[0].toLowerCase().includes('skill')
    );
    
    if (skillsTable) {
      const tableName = Object.values(skillsTable)[0];
      console.log(`\n🔍 检查表结构: ${tableName}`);
      
      // 查看表结构
      const [columns] = await connection.execute(`DESCRIBE ${tableName}`);
      console.log('📝 表结构:');
      columns.forEach(col => {
        console.log(`   - ${col.Field}: ${col.Type} ${col.Null === 'YES' ? '(可空)' : '(非空)'}`);
      });
      
      // 查看数据
      const [data] = await connection.execute(`SELECT COUNT(*) as count FROM ${tableName}`);
      console.log(`📊 数据条数: ${data[0].count}`);
    }
    
    await connection.end();
    console.log('\n✅ 连接测试完成！');
    
  } catch (error) {
    console.error('❌ 连接测试失败:', error.message);
    console.error('请检查以下配置:');
    console.error('1. MySQL服务是否启动');
    console.error('2. 数据库连接信息是否正确');
    console.error('3. 数据库和表是否存在');
  }
}

// 运行测试
testConnection(); 